<?php

namespace app\modules\admin\controllers;

use app\models\UserCardRecharge;
use yii\data\Pagination;
use yii\web\ForbiddenHttpException;

/**
 * 财务管理
 * Class FinanceController
 * @package app\modules\admin\controllers
 */
class FinanceController extends BaseController
{
    /**
     * 用户卡充值列表
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionUserCardRechargeList()
    {
        if (!$this->manager->can('finance/user-card-recharge')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $query = UserCardRecharge::find();
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('status ASC, id DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $rechargeList = $query->all();
        return $this->render('user_card_recharge_list', [
            'rechargeList' => $rechargeList,
            'pagination' => $pagination,
        ]);
    }

    /**
     * 卡充值（更新套餐时长）AJAX接口
     * @return array
     */
    public function actionUserCardRechargeConfirm()
    {
        if (!$this->manager->can('finance/user-card-recharge')) {
            return ['error' => 'FORBIDDEN', 'message' => '没有权限。'];
        }

        $recharge = UserCardRecharge::findOne(['id' => $this->get('id')]);
        if (empty($recharge)) {
            return ['error' => 'NOT_FOUND', 'message' => '没有找到充值信息。'];
        }
        if ($recharge->status != UserCardRecharge::STATUS_PAID) {
            return ['error' => 'RECHARGE_STATUS', 'message' => '状态错误，无法更新。'];
        }
        $card = $recharge->card;
        if ($card->term_length_unit != $recharge->term_length_unit) {
            return ['error' => 'TERM_LENGTH_UNIT', 'message' => '充值有效期单位和卡有效期单位不符。'];
        }
        $card->updateCounters(['term_length' => $recharge->term_length]);
        $card->calcTermEnd();
        $recharge->updateAttributes(['status' => UserCardRecharge::STATUS_RECHARGE, 'update_time' => time()]);

        return [];
    }
}
